﻿namespace TestTool.GUI.Utils
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;

    internal class AdvancedParametersUtils
    {
        public static List<object> Deserialize(IEnumerable<XmlElement> elements, IEnumerable<Type> types)
        {
            List<object> list = new List<object>();
            Dictionary<string, Type> dictionary = new Dictionary<string, Type>();
            foreach (Type type in types)
            {
                dictionary.Add(type.Name, type);
            }
            foreach (XmlElement element in elements)
            {
                string localName = element.LocalName;
                if (dictionary.ContainsKey(localName))
                {
                    Type type2 = dictionary[localName];
                    XmlNodeReader xmlReader = new XmlNodeReader(element);
                    object item = new XmlSerializer(type2).Deserialize(xmlReader);
                    list.Add(item);
                }
            }
            return list;
        }

        public static List<XmlElement> Serialize(IEnumerable<object> settings)
        {
            MemoryStream w = new MemoryStream();
            XmlFragmentWriter writer = new XmlFragmentWriter(w, new UTF8Encoding(false));
            int num = 0;
            foreach (object obj2 in settings)
            {
                if (obj2 != null)
                {
                    num++;
                    new XmlSerializer(obj2.GetType()).Serialize((XmlWriter) writer, obj2);
                }
            }
            if (num > 0)
            {
                writer.WriteEndElement();
            }
            writer.Close();
            string str = Encoding.UTF8.GetString(w.GetBuffer());
            XmlDocument document = new XmlDocument();
            if (!string.IsNullOrEmpty(str))
            {
                document.LoadXml(str);
            }
            List<XmlElement> list = new List<XmlElement>();
            if (document.DocumentElement != null)
            {
                foreach (XmlElement element in document.DocumentElement.ChildNodes)
                {
                    list.Add(element);
                }
            }
            return list;
        }
    }
}

